#include "aliyuntts.h"
#include <QDebug>

/**
 * @brief AliyunTts::AliyunTts
 * @param parent
 * 调用阿里云的语音合成接口来合成语音
 */


AliyunTts::AliyunTts(QObject *parent) : QObject(parent)
{
    player = new QMediaPlayer;
}

void AliyunTts::aliyunPlay(QString text, QString voice, QString rate, QString pitch, QString volume, QString format)
{
    // 创建一个网络请求管理器
    QNetworkAccessManager manager;
    // 创建一个HTTP请求
    QNetworkRequest request(QUrl("https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts"));
    // 设置HTTP请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    // 创建POST数据
    QJsonObject jsonData;
    jsonData["appkey"] = "Pjr2Vnl6lhN3OgLL";
    jsonData["token"] = "36f91bac4e0f4718b2f3fbbd15a8acb9";
    jsonData["text"] = text;
    jsonData["voice"] = voice;
    jsonData["speech_rate"] = rate;
    jsonData["pitch_rate"] = pitch;
    jsonData["volume"] = volume;
    jsonData["format"] = format;
    jsonData["sample_rate"] = "16000";
    QJsonDocument doc(jsonData);
    QByteArray postData = doc.toJson();

    // 发起POST请求
    QNetworkReply *reply = manager.post(request, postData);

    // 创建事件循环，等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // 处理响应
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray responseData = reply->readAll();

        // 将responseData写入文件
        QFile mp3File("/home/mhc/aliyun_output.mp3");
        if (mp3File.open(QIODevice::WriteOnly)) {
             mp3File.write(responseData);
             mp3File.close();
             qDebug() << "文件已成功写入。";
         } else {
             qDebug() << "无法打开文件进行写入。";
         }
     } else {
         qDebug() << "Error: " << reply->errorString();
     }

    // 释放资源
    reply->deleteLater();

    player->setMedia(QUrl::fromLocalFile("/home/mhc/aliyun_output.mp3"));
    player->play();
}

AliyunTts::~AliyunTts()
{
    delete player;
}
